﻿using System;
using System.Net;
using System.Windows;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls.Maps;
using System.Device.Location;
using System.Linq;

namespace SimpleRadar
{
    public class BingMapEx
    {

        public event EventHandler<FindByLocationCompletedEventArgs> FindByLocationCompleted;
        protected virtual void OnFindByLocationCompleted(FindByLocationCompletedEventArgs e)
        {
            EventHandler<FindByLocationCompletedEventArgs> handler = FindByLocationCompleted;
            if (handler != null)
            {
                handler(this, e);
            }
        }
        public void FindByLocation(double _long,double _lat)
        {
            BingMapGeocodeService.ReverseGeocodeRequest request = new BingMapGeocodeService.ReverseGeocodeRequest();
            request.Credentials = new Microsoft.Phone.Controls.Maps.Credentials();
            request.Credentials.ApplicationId = Global.ApplicationID;
            System.Device.Location.GeoCoordinate location = new System.Device.Location.GeoCoordinate();
            location.Latitude = _lat;
            location.Longitude = _long;
            request.Location = location;
            BingMapGeocodeService.GeocodeServiceClient geocodeClient = new BingMapGeocodeService.GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
            geocodeClient.ReverseGeocodeCompleted += (s, e) =>
            {
                if (e.Result.Results.Count > 0)
                {
                    FindByLocationCompletedEventArgs args=new FindByLocationCompletedEventArgs();

                    args.Result = e.Result.Results[0].DisplayName;

                    OnFindByLocationCompleted(args);
                }
            };
            geocodeClient.ReverseGeocodeAsync(request);
        }

        public event EventHandler<FindByAddressEventArgs> FindByAddressCompleted;
        protected virtual void OnFindByAddressCompleted(FindByAddressEventArgs e)
        {
            EventHandler<FindByAddressEventArgs> handler = FindByAddressCompleted;
            if (handler != null)
            {
                handler(this, e);
            }
        }
        public void FindByAddress(string Address)
        {
            BingMapGeocodeService.GeocodeRequest geocodeRequest = new BingMapGeocodeService.GeocodeRequest();
            geocodeRequest.Credentials = new Microsoft.Phone.Controls.Maps.Credentials();
            geocodeRequest.Credentials.ApplicationId = Global.ApplicationID;
            if (Address == null || Address == "")
            {
                geocodeRequest.Query = "  16.4625 ,  107.5869";// Bệnh viện trung ương Huế
            }
            else
                geocodeRequest.Query = Address.Trim();

            BingMapGeocodeService.FilterBase[] filter = new BingMapGeocodeService.FilterBase[1];
            filter[0] = new BingMapGeocodeService.ConfidenceFilter() { MinimumConfidence = BingMapGeocodeService.Confidence.High };
            BingMapGeocodeService.GeocodeOptions geocodeOptions = new BingMapGeocodeService.GeocodeOptions();
            geocodeOptions.Filters = new ObservableCollection<BingMapGeocodeService.FilterBase>(filter);
            geocodeRequest.Options = geocodeOptions;
            BingMapGeocodeService.GeocodeServiceClient geocodeService = new BingMapGeocodeService.GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
            geocodeService.GeocodeCompleted += (s, e) =>
            {
                List<Microsoft.Phone.Controls.Maps.Pushpin> pushpins = new List<Microsoft.Phone.Controls.Maps.Pushpin>();
                FindByAddressEventArgs args = new FindByAddressEventArgs();

                if (e.Result.Results.Count > 0)
                {
                    foreach (var Result in e.Result.Results)
                    {
                        Pushpin pushpin = new Pushpin() ;
                        pushpin.Location = new GeoCoordinate(Result.Locations[0].Latitude, Result.Locations[0].Longitude);
                        pushpins.Add(pushpin);
                    }
                    args.Messager = "Đã có kết quả trả về";
                    args.Pushpins = pushpins;
                }
                else
                {
                    args.Messager = "Không tìm thấy kết quả nào";
                }
                OnFindByAddressCompleted(args);
                pushpins.Clear();
            };
            geocodeService.GeocodeAsync(geocodeRequest);
        }

        public event EventHandler<GetRouteCompletedEventArgs> GetRouteCompleted;
        protected virtual void OnGetRouteCompleted(GetRouteCompletedEventArgs e)
        {
            EventHandler<GetRouteCompletedEventArgs> handler = GetRouteCompleted;
            if (handler != null)
            {
                handler(this, e);
            }
        }


        public void GetRouteLine(Map map1,List<GeoCoordinate> locations)
        {
            MapLayer RouteLayer = new MapLayer();

            BingMapRouteService.RouteServiceClient routeService = new BingMapRouteService.RouteServiceClient("BasicHttpBinding_IRouteService");

            routeService.CalculateRouteCompleted += (sender, e) =>
            {
                var points = e.Result.Result.RoutePath.Points;

                var coordinates = points.Select(x => new GeoCoordinate(x.Latitude, x.Longitude));

                var routeColor = Colors.Blue;

                var routeBrush = new SolidColorBrush(routeColor);

                var routeLine = new MapPolyline()
                {
                    Locations = new LocationCollection(),
                    Stroke = routeBrush,
                    Opacity = 0.65,
                    StrokeThickness = 5.0,
                };

                foreach (var location in points)
                {
                    routeLine.Locations.Add(new GeoCoordinate(location.Latitude, location.Longitude));
                }
                RouteLayer.Children.Add(routeLine);

                GetRouteCompletedEventArgs args = new GetRouteCompletedEventArgs();

                args.Result = RouteLayer;

                OnGetRouteCompleted(args);

                //var CheckChildren = map1.Children.Where(s => s == RouteLayer);
                //if (CheckChildren.Count() > 0)
                //    map1.Children.Remove(CheckChildren.First());
                //map1.Children.Add(RouteLayer);
            };

            //map1.SetView(LocationRect.CreateLocationRect(locations));

            routeService.CalculateRouteAsync(new BingMapRouteService.RouteRequest()
            {
                Credentials = new Credentials()
                {
                    ApplicationId = Global.ApplicationID
                },
                Options = new BingMapRouteService.RouteOptions()
                {
                    RoutePathType = BingMapRouteService.RoutePathType.Points
                },
                Waypoints = new ObservableCollection<BingMapRouteService.Waypoint>(
                    locations.Select(x => new BingMapRouteService.Waypoint()
                    {
                        Location = x
                    }))
            });
        }
    }
    public class FindByLocationCompletedEventArgs : EventArgs
    {
        public string Result;
    }
    public class FindByAddressEventArgs : EventArgs
    {
        public List<Pushpin> Pushpins = new List<Pushpin>();
        public string Messager;
    }
    public class GetRouteCompletedEventArgs : EventArgs
    {
        public MapLayer Result;
    }
}
